#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>

#include <netinet/in.h>

/**
 * @author Kristina Kurian
 * @usage: client <IP>
 * @date: 03-10-2011
*/

#define BUFFER 1024
#define SERV_PORT 9877

int recv_all(int s, char *buf, int len) {
  int total = 0;
  int n;
  while (total < len) {
    n = recv(s, buf, len, 0);
    if (n == -1) {
      break;
    }
    total += n;
  }
  return (n == -1 ? -1 : total);
}

int send_all(int s, char *buf, int len) {
  int total = 0;
  int n;
  while (total < len) {
    n = send(s, buf, len, 0);
    if (n == -1) {
      break;
    }
    total += n;
  }
  return (n == -1 ? -1 : total);
}

int main(int argc, char **argv) {
  int sockfd;
  struct sockaddr_in servaddr;

  if (argc != 3) {
    printf("ERROR: Wrong initial parametr!");
    return 1;
  }

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd == -1) {
    printf("ERROR: Could not create socket.\n");
    return 1;
  }
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(SERV_PORT);
  inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

  if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
    printf("ERROR: connect!");
    return 1;
  }
  
  int len = strlen(argv[2]);

  if (send_all(sockfd, argv[2], len) == -1) {
    printf("ERROR: could not transmittimg message.\n");
    close(sockfd);
    return 1;
  }
  
  char recv[BUFFER];
  memset(recv, BUFFER, 0);
  if (recv_all(sockfd, recv, len) == -1) {
    printf("ERROR: could not transmittimg message.\n");
    close(sockfd);
    return 1;
  }
  
  fputs(recv, stdout);
  close(sockfd);
  return 0;
}
